package cn.silver.framework.openapi.model;

import cn.silver.framework.openapi.constant.ResultEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serial;
import java.io.Serializable;

/**
 * 响应信息主体
 *
 * @author Silver Zhou
 */
@Data
@NoArgsConstructor
@Schema(name = "Result", title = "http请求结果对象", description = "http请求返回的响应结果对象")
public class Result<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    @Schema(title = "响应状态码")
    private int code;

    @Schema(title = "响应消息")
    private String message;

    @Schema(title = "响应结果集")
    private T data;

    public static <T> Result<T> ok() {
        return restResult(ResultEnum.SUCCESS.getCode(), "操作成功");
    }

    public static <T> Result<T> ok(T data) {
        return restResult(ResultEnum.SUCCESS.getCode(), "操作成功", data);
    }

    public static <T> Result<T> ok(String msg) {
        return restResult(ResultEnum.SUCCESS.getCode(), msg);
    }

    public static <T> Result<T> ok(String msg, T data) {
        return restResult(ResultEnum.SUCCESS.getCode(), msg, data);
    }

    public static <T> Result<T> fail() {
        return restResult(ResultEnum.ERROR.getCode(), "操作失败");
    }

    public static <T> Result<T> fail(String msg) {
        return restResult(ResultEnum.ERROR.getCode(), msg);
    }

    public static <T> Result<T> fail(int code, String msg) {
        return restResult(code, msg);
    }

    public static <T> Result<T> fail(ResultEnum result) {
        return restResult(result.getCode(), result.getMessage());
    }

    private static <T> Result<T> restResult(int code, String msg) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setMessage(msg);
        return result;
    }

    private static <T> Result<T> restResult(int code, String msg, T data) {
        Result<T> result = restResult(code, msg);
        result.setData(data);
        return result;
    }
}
